var defaultParams; //默认选中行
var menuId; //菜单栏父元素ID
var tableData; //定义列表名称
var selectId; //定义组织选中ID
var selectName; //定义组织选中名称
var changeSelectName; //选择改变时的值
var changeSelectId
    // 删除
function deleteTr() {
    if (defaultParams) {
        var ids = [defaultParams.questionId]
        layer.confirm('确定删除选中？', {
            title: "温馨提示",
            btn: ['确定', '取消'] //按钮
        }, function() {
            defaultParams = ""
            $.ajax({
                type: "post",
                url: "/operation/question/delete",
                dataType: "json",
                contentType: 'application/json',
                data: JSON.stringify({ "ids": ids }),
                cache: false,
                success: function(data) {
                    if (data.message === "成功") {
                        layer.msg('删除成功', { time: 1000, icon: 1 });
                        $("#table").bootstrapTable('refresh');
                    } else {
                        layer.msg('删除失败', { time: 1000, icon: 1 });

                    }

                },
                error: function() {
                    layer.msg('请求出错');
                }
            })
        }, function() {
            layer.msg('删除操作取消', {
                time: 2000
            });
            defaultParams = ""
            $("#table").bootstrapTable('refresh');
        });
    } else {
        layer.msg('请选择删除项');
    }

}
//返回
function back() {
    $("#buttonBack").hide()
    $("#buttonAdd").show()
    $("#buttonModify").show()
    $("#buttonDelete").show()
    $(".buttonSearchBox").show()
    $(".bootstrap-table").show()
    $(".contentInput").hide()
    $("#table").bootstrapTable('refresh');
    defaultParams = ""
    $("#submitButton").attr("disabled", false)
    saveFlag = true
}
//修改
function modify() {
    if (defaultParams) {
        $.ajax({
            url: "/operation/question/" + defaultParams["questionId"],
            type: "get",
            dataType: "json",
            cache: false,
            success: function(data) {

                if (data.message === "成功") {
                    $("#problemType").val(data.data.questionName)
                    $("#moreDesc").val(data.data.remark)
                    $("#warningInfo").val(data.data.warningInfo)
                    if (data.data.isSupportTransform == "1") {
                        $("#isSend").html('<label class="radio-inline"><input type="radio" name="send" checked  value="1">是 </label><label class="radio-inline"><input type="radio" name="send" value="0">否</label>')

                    } else {
                        $("#isSend").html('<label class="radio-inline"><input type="radio" name="send"   value="1">是 </label><label class="radio-inline"><input type="radio" name="send" checked value="0">否</label>')

                    }
                    if (data.data.isEndding == "1") {
                        $("#isSolve").html('<label class="radio-inline"><input type="radio" name="solve" checked  value="1">是 </label><label class="radio-inline"><input type="radio" name="solve"  value="0">否</label>')

                    } else {
                        $("#isSolve").html('<label class="radio-inline"><input type="radio" name="solve"   value="1">是 </label><label class="radio-inline"><input checked type="radio" name="solve"  value="0">否</label>')

                    }
                    //是否显示运营部专用
                    if (data.data.channelType == "2") {
                        $(".tips").show()
                    } else {
                        $(".tips").hide()
                    }
                    var options = $("#menuName option")
                    for (var i = 0; i < options.length; i++) {

                        if (data.data.menuId == $(options[i]).attr("menuid")) { //根据系统通道判断当前对应菜单项
                            $("#menuName").val($(options[i]).val())
                                // 根据菜单项 页面默认选中的系统通道
                            $.ajax({
                                type: "get",
                                url: "/operation/channel/getChannelByMenu",
                                dataType: "json",
                                contentType: 'application/json',
                                data: { "menuId": data.data.menuId, "isOperation": data.data.channelType == "1" ? false : true },
                                cache: false,
                                success: function(msg) {
                                    systermRouteData("#systermRoute", msg.data)
                                },
                                error: function(e) {
                                    if (e.status == 500) {
                                        layer.msg("系统错误");
                                        return
                                    } else if (e.responseText) {
                                        var errorMessage = JSON.parse(e.responseText).errors[0].message;
                                        layer.msg(errorMessage);
                                    }
                                }
                            });
                        } else {
                            $(options[i]).attr("selected", false)
                        }
                    }
                    // 渲染流程表格 
                    if (data.data && data.data.questionFlowList) {
                        var tableFlow = data.data.questionFlowList.sort(compare("sort"));
                        var strTable = ""
                        for (var i = 0; i < tableFlow.length; i++) {
                            if (i == 0) {
                                var id = tableFlow[i].orgId
                                strTable += '<tr><td><span >1</span></td><td><span>无</span></td><td><span>无</span> </td><td><span>系统默认无法操作</span></td></tr>'
                            } else {
                                if (tableFlow[i].orgLevel == 13) {
                                    var id = tableFlow[i].orgId ? tableFlow[i].orgId : "000000";
                                    strTable += '<tr><td><span >' + tableFlow[i].sort + '</span></td><td><span iddata="' + id + '" >' + getSingleData(id) + '</span> </td><td><span>分部</span><select name="" style="display:none" class="re_age form-control"> <option value="无">无</option><option value="分部">分部</option></select></td><td><button  class="btn btn-red change" >修改</button> <button type="button" class="btn que_change" style="display:none">确定</button> <button type="button" class="btn del_change">删除</button></td></tr>'
                                } else if (tableFlow[i].orgLevel == 12) {
                                    var id = tableFlow[i].orgId ? tableFlow[i].orgId : "000000";
                                    strTable += '<tr><td><span >' + tableFlow[i].sort + '</span></td><td><span iddata="' + id + '" >' + getSingleData(id) + '</span> </td><td><span>总部</span><select name="" style="display:none" class="re_age form-control"> <option value="无">无</option><option value="分部">分部</option></select></td><td><button  class="btn btn-red change" >修改</button> <button type="button" class="btn que_change" style="display:none">确定</button> <button type="button" class="btn del_change">删除</button></td></tr>'
                                } else {
                                    var id = tableFlow[i].orgId ? tableFlow[i].orgId : "000000";
                                    strTable += '<tr><td><span >' + tableFlow[i].sort + '</span></td><td><span iddata="' + id + '" >' + getSingleData(id) + '</span> </td><td><span>无</span><select name="" style="display:none" class="re_age form-control"> <option value="无">无</option><option value="分部">分部</option></select></td><td><button  class="btn btn-red change" >修改</button> <button type="button" class="btn que_change" style="display:none">确定</button> <button type="button" class="btn del_change">删除</button></td></tr>'

                                }
                            }
                        }
                        $("#questionFlowList tbody").html(strTable)
                    }



                }
            },
            error: function(e) {
                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        $("#buttonBack").show()
        $("#buttonAdd").hide()
        $("#buttonModify").hide()
        $("#buttonDelete").hide()
        $(".buttonSearchBox").hide()
        $(".bootstrap-table").hide()
        $(".contentInput").show()
        $(".contentInput input").attr("disabled", false)
        $(".contentInput select").attr("disabled", false)
        $(".contentInput textarea").attr("disabled", false)
        $("#submitButton").show()
        $("#saveButton").show()
    } else {
        layer.msg('请选择一项修改');
    }
}
//增加
function add() {
    defaultParams = ""
    $("#buttonBack").show()
    $("#buttonAdd").hide()
    $("#buttonModify").hide()
    $("#buttonDelete").hide()
    $(".buttonSearchBox").hide()
    $(".bootstrap-table").hide()
    $(".contentInput").show()
    $("#submitButton").show()
    $("#systermToute").html("")
    $("#moreDesc").val("")
    $("#problemType").val("")
    $("#warningInfo").val("")
    $("#questionFlowList tbody").html('<tr><td><span>1</span></td><td><span iddata="000000">无</span> </td><td><span>无</span></td><td><span>系统默认无法操作</span></td></tr>')
    $("#menuName").val("")
    $("#systermRoute").val("")
    $("#isSend").html('<label class="radio-inline"><input type="radio" name="send" checked  value="1">是 </label><label class="radio-inline"><input type="radio" name="send" value="0">否</label>')
    $("#isSolve").html('<label class="radio-inline"><input type="radio" name="solve" checked  value="1">是 </label><label class="radio-inline"><input type="radio" name="solve"  value="0">否</label>')
}


// 根据菜单获取系统通道s
$("#menuName").on("change", function() {
    if ($("#menuName option:selected").attr("menuId")) {
        $.ajax({
            type: "get",
            url: "/operation/channel/getChannelByMenu",
            dataType: "json",
            contentType: 'application/json',
            data: { "menuId": $("#menuName option:selected").attr("menuId") },
            cache: false,
            success: function(msg) {
                systermRouteData("#systermRoute", msg.data)
            },
            error: function(e) {

                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        });
    }

})

// 根据菜单获取系统通道e
//enter搜索
function noNumbers(e) {
    var keynum;
    var keychar;

    keynum = window.event ? e.keyCode : e.which;
    if (keynum == "13") {
        search()
    }
}
// 搜索
function search() {

    defaultParams = ""
    $("#table").bootstrapTable('destroy');
    tableData.initData()
}
//删除搜索关键字
function removeSearchVal() {
    $("#searchVal").val("")
    $("#searchVal").focus()
}
//提交
function submitButtonEvent() {

    var trs = $("#questionFlowList tbody tr")
    var arrSubmit = []
        //组织和组织层级为必填标记
    var orgFlag = true; //默认可以提交
    for (var i = 0; i < trs.length; i++) {
        arrSubmit[i] = {}
        arrSubmit[i]["sort"] = trs.eq(i).children("td").eq(0).children("span").eq(0).html()
        if (trs.eq(i).children("td").eq(2).children("span").eq(0).html() == "总部") {
            arrSubmit[i]["orgLevel"] = 12
        } else if (trs.eq(i).children("td").eq(2).children("span").eq(0).html() == "分部") {
            arrSubmit[i]["orgLevel"] = 13
        } else {
            arrSubmit[i]["orgLevel"] = ""
        }
        arrSubmit[i]["orgId"] = trs.eq(i).children("td").eq(1).children("span").eq(0).attr("iddata") == "000000" ? "" : trs.eq(i).children("td").eq(1).children("span").eq(0).attr("iddata")

        if (i > 0) {
            if (!arrSubmit[i]["orgLevel"] && !arrSubmit[i]["orgId"]) {

                orgFlag = false
            } else if (arrSubmit[i]["orgLevel"] && arrSubmit[i]["orgId"]) {
                orgFlag = false
            }
        }


    }
    if (saveFlag && orgFlag) {
        var params = {
            "questionName": $("#problemType").val(),
            "menuId": $("#menuName option:selected").attr("menuId"),
            "channelId": $("#systermRoute option:selected").attr("channelid"),
            "questionFlowList": arrSubmit,
            "warningInfo": $("#warningInfo").val(),
            "isSupportTransform": $("#isSend input[type='radio']:checked").val() == "1" ? 1 : 0,
            "isEndding": $("#isSolve input[type='radio']:checked").val() == "1" ? 1 : 0
        }
        $table = $('#table')
        if (defaultParams.questionId) { //修改
            $.ajax({
                type: "POST",
                contentType: 'application/json',
                url: "/operation/question/" + defaultParams.questionId,
                data: JSON.stringify(params),
                dataType: "json",
                cache: false,
                success: function(data) {
                    layer.msg('修改成功', { time: 1000, icon: 1 });
                    $("#submitButton").attr("disabled", true)
                    $("#table").bootstrapTable('refresh');
                    back()
                },
                error: function(e) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            })
        } else { //新增
            $.ajax({
                    type: "post",
                    url: "/operation/question/",
                    contentType: 'application/json',
                    data: JSON.stringify(params),
                    dataType: "json",
                    cache: false,
                    success: function(data) {
                        layer.msg('提交成功', { time: 1000, icon: 1 });
                        $("#submitButton").attr("disabled", true)
                        $("#table").bootstrapTable('refresh');
                        back()
                    },
                    error: function(e) {
                        if (e.responseText) {
                            var errorMessage = JSON.parse(e.responseText).errors[0].message;
                            layer.msg(errorMessage);
                        }

                    }
                })
                //
        }
    } else if (saveFlag && !orgFlag) {
        layer.msg('组织层级和组织有且只能填一项');
    } else {
        layer.msg('请先处理完成当前列表');
    }

    return false
}

// 系统通道数据
function systermRouteData(id, arr) {
    var str = ''
    for (var i = 0; i < arr.length; i++) {
        if (defaultParams.channelId && defaultParams.channelId == arr[i].channelId) {
            str += '  <option selected channelId="' + arr[i]['channelId'] + '">' + arr[i]['channelName'] + '</option>'
        } else {
            str += '  <option channelId="' + arr[i]['channelId'] + '">' + arr[i]['channelName'] + '</option>'
        }

    }
    $(id).html(str)
}
// 渲染页面菜单数据s


var str = '<option value=""></option>'
//var dataArr = data.data
//for (var i = 0; i < dataArr.length; i++) {
        str += '  <option menuid="' + 1234["menuId"] + '"   value="' + 5678["menuName"] + '">' + 1234["menuName"] + '</option>'
//    }
    $("#menuName").html(str)

//$.ajax({
//    url: "/operation/system/menu/getMenuSelect",
//    type: "get",
//    dataType: "json",
//    cache: false,
//    success: function(data) {
//        if (data.message === "成功") {
//            var str = '<option value=""></option>'
//            var dataArr = data.data
//            for (var i = 0; i < dataArr.length; i++) {
//                str += '  <option menuid="' + dataArr[i]["menuId"] + '"   value="' + dataArr[i]["menuName"] + '">' + dataArr[i]["menuName"] + '</option>'
//            }
//            $("#menuName").html(str)
//        }
//
//    },
//    error: function(e) {
//
//        if (e.status == 500) {
//            layer.msg("系统错误");
//            return
//        } else if (e.responseText) {
//            var errorMessage = JSON.parse(e.responseText).errors[0].message;
//            layer.msg(errorMessage);
//        }
//    }
//})

// 渲染页面菜单数据e

$(".saveSelectPart").on("click", function() {
    $("#dragSelect").html('<option selected  value="">' + changeSelectName + '</option>')
    $("#dragSelect").attr("iddata", changeSelectId)
    $(".close").click()
})
$("#questionFlowList").on("click", $("#dragSelect"), function(e) {
    $(".searchable-select").eq(1).remove()
    if (e.target.id == "dragSelect") {
        var clickId = $(e.target).eq(0).attr("iddata")
        var clickHtml = $(e.target).children("option").eq(0).html()
        if (clickId) {
            $("#belongPart").val(clickId)
            $('#belongPart').searchableSelect();
            $(".searchable-select").eq(1).remove()
        }

    }


    // 
})

function getSingleData(id) {


    var selectList = $(".searchable-select-items .searchable-select-item")

    for (var i = 0; i < selectList.length; i++) {
        if (selectList.eq(i).attr("data-value") === id) {
            selectList.eq(i).addClass("selected").siblings().removeClass("selected")
            $(".searchable-select-holder").text(selectList.eq(i).text())
            return selectList.eq(i).html()
        }
    }
}
// 数组排序
function compare(property) {
    return function(a, b) {
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}
